import React, { useCallback, useEffect, useRef } from "react";
import { BaseEchartProps } from "./type";
import * as echarts from "echarts";
// import FullScreenBox from '@/components/FullScreenBox';
import "./index.less";
import { debounce } from "lodash";
function ChatEcharts(props: BaseEchartProps) {
  const { option = {} } = props;
  const chartRef = useRef<any>(null);
  const chartWrapperRef = useRef<any>(null);
  let chartInstanceRef = useRef<any>(null);

  // ! 移动端适配
  let title = option?.title ?? {};
  let legend = option?.legend ?? {};
  let titleTextStyle = title?.textStyle ?? {};
  title = {
    ...title,
    textStyle: {
      ...titleTextStyle,
      fontSize: 14,
      color: "#fff",
    },
  };
  legend = {
    ...legend,
    top: title?.text ? "20px" : "4px", // 设置图例距离顶部的高度
    orient: "horizontal", // 图例方向为水平
    align: "auto", // 图例对齐方式
    textStyle: {
      // fontSize: 12, // 设置图例字体大小
      color: "#fff",
    },
  };
  let cOption = {
    ...option,
    title,
    legend,
  };

  const renderChart = () => {
    const myChart = echarts.getInstanceByDom(chartRef.current as any);

    if (myChart) chartInstanceRef.current = myChart;
    else chartInstanceRef.current = echarts.init(chartRef.current as any);
  };

  const setChartOptions = () => {
    // 使用刚指定的配置项和数据显示图表。
    chartInstanceRef.current?.setOption(cOption, true);
  };

  const resize = useCallback(
    debounce(() => {
      if (chartInstanceRef.current) {
        chartInstanceRef?.current?.resize?.();
      }
    }, 100),
    []
  );
  useEffect(() => {
    renderChart();
    setChartOptions();
    const resizeObserver = new ResizeObserver((entries) => {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      for (let _entry of entries) {
        resize();
      }
    });

    if (chartWrapperRef.current) {
      resizeObserver.observe(chartWrapperRef.current);
    }

    return () => {
      resizeObserver.disconnect();
      if (!chartInstanceRef.current) {
        return;
      }

      chartInstanceRef.current.dispose();
      chartInstanceRef.current = null;
    };
  }, []);

  useEffect(() => {
    renderChart();
    setChartOptions();

    return () => {
      if (!chartInstanceRef.current) {
        return;
      }

      chartInstanceRef.current.dispose();
      chartInstanceRef.current = null;
    };
  }, []);

  return (
    <div
      // resize={resize}
      className="chat-echart-wrapper"
      ref={chartWrapperRef}
    >
      <div
        id="main"
        style={{ width: "100%", height: "100%" }}
        ref={chartRef}
      ></div>
    </div>
  );
}

export default ChatEcharts;
